﻿using Common.DictComponent;
using Model;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Service
{
    // 实现公共组件的 IRedisDictCacheService 接口
    public class RedisDictCacheService : IRedisDictCacheService
    {
        private readonly IDatabase _redisDb;

        // 原有构造函数不变
        public RedisDictCacheService(IConnectionMultiplexer redis)
        {
            _redisDb = redis.GetDatabase();
        }

        // 实现接口所有方法（复用原有Redis逻辑）
        public async Task<WmsDictType> GetDictTypeAsync(string code)
        {
            var cacheKey = $"Dict:Type:{code}";
            var cacheValue = await _redisDb.StringGetAsync(cacheKey);
            return cacheValue.HasValue ? JsonConvert.DeserializeObject<WmsDictType>(cacheValue) : null;
        }

        public async Task<List<WmsDictData>> GetDictDataListAsync(long typeId)
        {
            var cacheKey = $"Dict:Data:{typeId}";
            var cacheValue = await _redisDb.StringGetAsync(cacheKey);
            return cacheValue.HasValue ? JsonConvert.DeserializeObject<List<WmsDictData>>(cacheValue) : new List<WmsDictData>();
        }

        public async Task SetDictTypeAsync(WmsDictType dictType)
        {
            var cacheKey = $"Dict:Type:{dictType.Code}";
            var cacheValue = JsonConvert.SerializeObject(dictType);
            await _redisDb.StringSetAsync(cacheKey, cacheValue, TimeSpan.FromHours(24)); // 缓存24小时
        }

        public async Task SetDictDataListAsync(long typeId, List<WmsDictData> dictDataList)
        {
            var cacheKey = $"Dict:Data:{typeId}";
            var cacheValue = JsonConvert.SerializeObject(dictDataList);
            await _redisDb.StringSetAsync(cacheKey, cacheValue, TimeSpan.FromHours(24));
        }

        public async Task ClearDictTypeCacheAsync(string code)
        {
            var cacheKey = $"Dict:Type:{code}";
            await _redisDb.KeyDeleteAsync(cacheKey);
        }

        public async Task ClearDictDataCacheAsync(long typeId)
        {
            var cacheKey = $"Dict:Data:{typeId}";
            await _redisDb.KeyDeleteAsync(cacheKey);
        }
    }
}
